package com.tsfyun.scm.gateway.support.dd;

import com.tsfyun.scm.gateway.constant.TraceConstant;
import com.tsfyun.scm.gateway.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description:
 * @CreateDate: Created in 2020/12/18 12:29
 */
@Slf4j
public class DingTalkNoticeUtil {

    public static void send2DingDing(ServerHttpRequest request, List<String> dingdingUrl,String salt) {
        try {
            //如果是本地windows环境则不发送
            String osName = System.getProperties().getProperty("os.name");
            if (!StringUtils.isEmpty(osName) && osName.trim().toLowerCase().contains("windows")) {
                log.debug("本地windows环境，不推送钉钉消息");
                return;
            }
            String requestUrl = request.getPath().value();
            String ip = IpUtils.getIpAddress(request);
            String traceId = request.getHeaders().getFirst(TraceConstant.HTTP_HEADER_TRACE_ID);

            final String token = request.getHeaders().getFirst("token");
            final String requestBrowserName = request.getHeaders().getFirst("device");
            new Thread(() -> {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String crashTime = df.format(new Date());
                String text = "####xxxx请求频繁业务预警####\n" +
                        "> 请求地址： " + requestUrl + "\n\n" +
                        "> 跟踪ID： " + StringUtils.trimToEmpty(traceId) + "\n\n" +
                        "> 请求IP： " + ip + "\n\n" +
                        "> 设备： " + requestBrowserName + "\n\n" +
                        "> token： \n" + token + "\n\n" +
                        "> 时间： " + crashTime + " \n" +
                        "> ###### [封杀IP](https://xxxx.com/monitor/prohibitIp?ip=" + ip + "&acceptSalt=" + salt + ")";
                new ExceptionDingTalkMessage(new DingTalkMessageBuilder().markdownMessage("请求频繁预警", text).at(null),dingdingUrl).send();
            }).start();
        } catch (Exception oe) {
            log.error("发送至钉钉异常", oe);
        }
    }

    public static void send2DingDingException(ServerHttpRequest request, String title, Throwable e,List<String> dingdingUrl,String profile) {
        try {
            //如果是本地windows环境则不发送
            String osName = System.getProperties().getProperty("os.name");
            if (!StringUtils.isEmpty(osName) && osName.trim().toLowerCase().contains("windows")) {
                log.debug("本地windows环境，不推送钉钉消息");
                return;
            }
            if(Objects.equals(profile,"dev") || Objects.equals(profile,"test")) {
                return;
            }
            String requestUrl = request.getPath().value();
            String ip = IpUtils.getIpAddress(request);
            String traceId = request.getHeaders().getFirst(TraceConstant.HTTP_HEADER_TRACE_ID);

            final String token = request.getHeaders().getFirst("token");
            final String requestBrowserName = request.getHeaders().getFirst("device");
            new Thread(() -> {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String crashTime = df.format(new Date());
                String text = String.format("####xxxx%s业务预警####\n",title) +
                        "> 请求地址： " + requestUrl + "\n\n" +
                        "> 跟踪ID： " + StringUtils.trimToEmpty(traceId) + "\n\n" +
                        "> 请求IP： " + ip + "\n\n" +
                        "> 设备： " + requestBrowserName + "\n\n" +
                        "> token： \n" + token + "\n\n" +
                        "> 堆栈信息： \n" + (Objects.nonNull(e) ? e.getMessage() : "") + "\n\n" +
                        "> 出错时间： " + crashTime + " \n";
                new ExceptionDingTalkMessage(new DingTalkMessageBuilder().markdownMessage("服务转发失败预警", text).at(null),dingdingUrl).send();
            }).start();
        } catch (Exception oe) {
            log.error("发送至钉钉异常", oe);
        }
    }


    public static String sign(Long timestamp,String secret) {
        String stringToSign = timestamp + "\n" + secret;
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            return  URLEncoder.encode(new String(Base64.getEncoder().encode(signData)), "UTF-8");
        } catch (Exception e) {
            log.error("钉钉参数签名异常",e);
        }
        return null;
    }

}
